'use strict';

const Controller = require('egg').Controller;

class TopicController extends Controller {

  async getList() {
    const { ctx } = this;
    const [ option ] = ctx.getPageListOption();
    
    const listQuery = {};

    const topicList = await ctx.service.topic.getTopicList(listQuery, option) || [];
    const totalCount = await ctx.service.topic.getCountByQuery(listQuery);

    ctx.apiPageList(topicList, totalCount);
  }

  async getTopicList() {
    const { ctx } = this;
    const collectId = ctx.getQuery('collectId');

    const listQuery = {
      deleted: false,
    };

    if (collectId) {
      listQuery.category = collectId;
    }

    const [ option ] = ctx.getPageListOption()

    option.sort = 'date'

    const selected = ['_id', 'abstract', 'category', 'title', 'date', 'status', 'extensions'];
    const count = await ctx.model.Content.count(listQuery);
    const topicList = await ctx.model.Content.find(listQuery, selected, option).exec();

    ctx.apiPageList(topicList, count);
  }

  async getTopList() {
    const { ctx } = this;
    // const topicList = await ctx.service.topic.getTopicList({
    //   biz: 'TOP_HOME'
    // });
    const result = await ctx.service.cms.getTopicList(listQuery, option) || [];

    ctx.body = {
      success: true,
      topicList: result.data,
    };
  }

  async create(ctx) {
    const body = ctx.request.body;
    // 储存新主题帖
    const topic = await ctx.service.topic.newAndSave(
      body.title,
      body.content,
      body.biz,
      body.image,
      body.desc,
      body.tag
    );

    ctx.body = {
      success: true,
      topic_id: topic.id,
    };
  }
}

module.exports = TopicController;
